//
//  WM转发微博详情Controller.swift
//  GZWeibo007
//
//  Created by 汪明 on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit


//Bug,会崩溃 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds'
class WM转发微博详情Controller: UIViewController ,JwyBottomViewDelegate,UITableViewDelegate,UITableViewDataSource{
 
    private var newsview: WMfoolStatus = {
        
        let new = NSBundle.mainBundle().loadNibNamed("foot", owner: nil, options: nil).last as!WMfoolStatus
        
        
        return new
        
        
    }()
    var status: CZStatus?{
    
        didSet{
            
            
            CZComments.ZHLoadDiscussData((status?.id)!, since_id: 0, max_id: 0, count: 10, finished: { (comments, error) -> () in
                
                let count = comments?.count ?? 0
        
                
                if count != 0 {
                    
                    
                    self.comment = comments!
                   // print(self.comment[0].id)
                    //print(self.comment[1].id)
                    
                     self.head.pingLun.setTitle("评论 \(self.comment.count)", forState: .Normal)
                    
                    
                    
                }
        
            })
        }
    
    }
    

    var comment :[CZComments] = [] {
        
        didSet{
            
            self.tableView.reloadData()
            
        }
        
        
    }
    
  
    var tableView = UITableView()
    override func viewDidLoad() {
        super.viewDidLoad()
     
        
      self.view.addSubview(tableView)
        
      tableView.ff_Fill(self.view, insets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
        prepareBottomView()
        
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusNormalCell.rawValue)
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusForwardCell.rawValue)
        
        tableView.registerNib(UINib(nibName: "WM暂无评论Cell", bundle: nil), forCellReuseIdentifier: "WM暂无评论Cell")
        
        tableView.registerClass(WMpingLunCell.self, forCellReuseIdentifier: "WMpingLunCell")
         tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        
        self.tableView.separatorColor = UIColor.init(white: 0.95, alpha: 1.00)
        let cellview = UIView()
    
        self.tableView.tableFooterView = cellview
                
    }
    
    
    
//MARK:------添加底部试图
    func prepareBottomView(){
        self.view.addSubview(bottomView)
        //指定代理
        bottomView.delegate = self
        
        bottomView.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: self.view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44), offset: CGPoint(x: 0, y: 0))
    }
    
//MARK:-------- 懒加载底部视图
    var bottomView: JwyBottomView = JwyBottomView()
    
//MARK:---------实现底部按钮点击事件
    
    func jumpTo(btn:UIButton) {
        
        let vc=JwyZhuanfaController(tag: btn.tag)
        vc.statu=status
        
        let itemView=JwyitemView()//自定义titleView
        itemView.topLabel.text=btn.titleLabel!.text! + "微博"
        
        let userName=CZUserAccount.loadUserAccount()?.screen_name ?? "无用户名"
        itemView.userNameLabel.text=userName
        
        vc.navigationItem.titleView=itemView
        
        let nav=UINavigationController(rootViewController: vc)
        
        //跳转转发或者评论界面
        self.navigationController?.presentViewController(nav, animated: true, completion: nil)
        
    }
    
   
    
    
    ///注意不是这个方法确定组数,
//    func  numberOfRowsInSection(section: Int) -> Int {
//    
//      return 2
//    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        
        
        return 2
    }
    
    
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     
        return section == 0 ? 1 : comment.count == 0 ? 1 : comment.count
        
        
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            
            let cellID = status!.cellID()
            let cell = tableView.dequeueReusableCellWithIdentifier(cellID)
            as! CZStatusCell
            cell.bottomView.removeFromSuperview()
            if  cell is CZStatusForwardCell {
                
                
                let ce = cell as! CZStatusForwardCell
                ce.tag = indexPath.row
                ce.bkgButton.removeFromSuperview()
                ce.addSubview(ce.bkgButton)
              
                ce.bkgButton.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: ce.contentLabel, size: nil,offset: CGPoint(x: -8, y: 8))
                ce.addConstraint( NSLayoutConstraint(item: ce.bkgButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: ce.pictureView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
                ce.addConstraint(NSLayoutConstraint(item: ce.bkgButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: ce, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
                
                
                 ce.sendSubviewToBack(ce.bkgButton)
              
                
            }
            
            cell.status = status
            
            
            
            return cell
        }
        else
        {
        
            if comment.count != 0 {
                let cell  = tableView.dequeueReusableCellWithIdentifier("WMpingLunCell") as! WMpingLunCell
                
                cell.comment = comment[indexPath.row]
                
                return cell
                
            }
            
            
            let cell = tableView.dequeueReusableCellWithIdentifier("WM暂无评论Cell")
            
        
            return cell!
      
        }
        
        
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        
        let cell = tableView.cellForRowAtIndexPath(indexPath)
        
        if cell is CZStatusForwardCell {
        
        
           self.WM转发cell的事件()
        }
        
        
    }

    
    func WM转发cell的事件(){
       
        
        let view = WM转发微博详情Controller()
        
        view.status = status!.retweeted_status
        
        
        self.navigationController?.pushViewController(view, animated: true)
      
    }
    
    
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
             let cellID = status!.cellID()
                let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! CZStatusCell
                
                
                var row = status?.rowHeight
                
                
                if row == nil {
                    
                    row = cell.rowHeight(status!)
                    
                    status?.rowHeight = row
                    
                }
                
                
                return row! - 44
            
        }else if indexPath.section == 1 {
            
            if comment.count != 0 {
                let cell = tableView.dequeueReusableCellWithIdentifier("WMpingLunCell") as! WMpingLunCell
                
                
                let row = cell.rowHeight(comment[indexPath.row])
                
                return row + 10
            
            }
        }
        
        return 80
        
   }
    
    ///微博详情cell的底部view
    private lazy var head: WMpingLunZan = {
    
       let head = NSBundle.mainBundle().loadNibNamed("WMpingLunZan", owner: nil, options: nil).last as! WMpingLunZan
        
        
        return head
    
    }()
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        head.statu = status
        
        head.refreshPingLun = {
            
            let new = NSBundle.mainBundle().loadNibNamed("foot", owner: nil, options: nil).last as!WMfoolStatus
            
            new.jiuHua.hidden = true
            self.head.addSubview(new)
            new.ff_AlignVertical(type: ff_AlignType.BottomCenter, referView: self.head, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 80))
            
            //加载最新评论
            self.loadTheLatestComments()
            self.head.pingLun.setTitle("评论 \(self.comment.count)", forState: .Normal)
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                
                //删除加载按钮
                new.removeFromSuperview()
            })
         
        }
        
        head.refreshZhuanFa = {
        
         
         
        }
        
         head.refreshZan = {
        
         
        }
        
        return   section == 0 ?  nil : head
 
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return section == 0 ? 0 : head.height
        
    }
    
    ///加载最新评论
    func loadTheLatestComments(){
        
        
        
         let id = self.comment.first?.id ?? 0
        
            CZComments.ZHLoadDiscussData((status?.id)!, since_id: id, max_id: 0, count: 10, finished: { (comments, error) -> () in
                
                let count = comments?.count ?? 0
                if count != 0 {
                    
                    
                    self.comment = comments! + self.comment
                    
                    self.status?.comments_count = self.comment.count
                    
                    
                }else{
                    //隐藏刷新按钮
                    self.newsview.hidden = true
                    
                }
                
            })

        
        
        
        
        
    }
    
    
    ///加载更多评论
    func loadMoreComments(){
        
         let id = self.comment.last?.id ?? 0
        
        
            CZComments.ZHLoadDiscussData((status?.id)!, since_id: 0, max_id: id, count: 10) { (comments, error) -> () in
                
                let count = comments?.count ?? 0
                if count != 0 {
                    
                    
                    self.comment = self.comment + comments!
                    self.status?.comments_count = self.comment.count
                    
                }else{
                    
                    print("没有更多评论")
                    //隐藏刷新按钮
                    self.newsview.hidden = true
                }
                
            }

        
        
    }

}


///MARK:scrollView的代理实现
extension WM转发微博详情Controller: UIScrollViewDelegate {

   
    //UITableView滚动的时候调用
     func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //判断偏移值加tableView的高度,是否大于contentSize的高度 + 80
        if tableView.contentOffset.y + self.tableView.height > self.tableView.contentSize.height + 80 {
            
            //显示遮罩按钮的选中状态
            self.newsview.jiuHua.selected = true
            
        }else
        {
            //关闭遮罩按钮的选中状态
            self.newsview.jiuHua.selected = false
        }
    }
    
    
    
    ///scrollView完成拖拽的时候调用
     func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        
        if self.newsview.jiuHua.selected {
            
            self.newsview.jiuHua.hidden = true
            
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                
                
                self.loadMoreComments()
                
            })
            
        }else{
            
            self.newsview.jiuHua.hidden = false
        }
        
        self.tableView.tableFooterView = self.newsview
        
        
    }

}








































